<template>
  <div class="page_main">
    <div class="search_box">
      <el-form ref="searchForm" :inline="true" :model="searchForm" size="mini">
        <search-form-box :show-more-btn="false">
          <template slot="showSearch">
            <el-form-item label="到款开始时间" prop="begin_time">
              <el-date-picker
                v-model="searchForm.begin_time"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择开始时间"
              />
            </el-form-item>
            <el-form-item label="至" prop="end_time">
              <el-date-picker
                v-model="searchForm.end_time"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择结束时间"
              />
            </el-form-item>
            <el-form-item label="客户" prop="customer_id">
              <el-select v-model="searchForm.customer_id" filterable clearable style="width: 200px">
                <el-option v-for="item in customerArr" :key="item.id" :value="item.id" :label="item.name"/>
              </el-select>
            </el-form-item>
          </template>
          <template slot="searchBtn">
            <el-form-item>
              <el-button size="mini" type="primary" plain @click="search">查询</el-button>
              <el-button size="mini" type="info" plain @click="resetForm('searchForm')">重置</el-button>
            </el-form-item>
          </template>
        </search-form-box>
      </el-form>
    </div>
    <el-row style="margin-bottom: 10px">
      <el-button v-permission="'add_account_received'" size="mini" type="primary"
                 @click="showAddDialog"
      >
        新增到款
      </el-button>
      <el-tooltip effect="dark" content="确定数据无误后，将无法修改和删除,确定后的数据销售才可见"
                  placement="top"
      >
        <el-button v-permission="'confirm_account_received'" :disabled="selectArr.length === 0" size="mini"
                   type="warning" @click="batchConfirm"
        >
          批量确认
        </el-button>
      </el-tooltip>
    </el-row>
    <div class="data_box">
      <el-table v-loading="tableLoading" :data="listData" border size="mini" @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          width="55"
          :selectable="(row)=>{return !row.confirm}"
        >
        </el-table-column>
        <el-table-column fixed="left" width="50" label="序号" align="center">
          <template slot-scope="scope">
            <span>{{ (listParams.page - 1) * listParams.page_size + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否关联组别" width="120" align="center">
          <template slot-scope="scope">
            <el-tag size="mini" v-if="scope.row.group_id !== null" type="success">已关联</el-tag>
            <el-tag size="mini" v-else type="danger">未关联</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="到款时间" min-width="120" prop="account_received_time" align="center"/>
        <el-table-column label="付款客户" min-width="120" prop="customer_name" align="center"/>
        <el-table-column label="到款金额" min-width="120" prop="account" align="center"/>
        <el-table-column label="组别销售单信息" min-width="120" prop="account" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.billSaleVOS &&scope.row.billSaleVOS.length">
              <div v-for="(item,index) in scope.row.billSaleVOS" :key="index">
                {{ item.contract_num + '——' + item.actual_execute_time_start + '~' + item.actual_execute_time_end }}
              </div>
            </div>
            <div v-else>
              暂无信息
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button-group>
              <el-button class="group_btn" v-if="!scope.row.confirm" v-permission="'edit_account_received'"
                         type="primary" size="mini"
                         @click="showEditDialog(scope.row)"
              >修改
              </el-button>
              <el-tooltip v-if="!scope.row.confirm" class="group_btn" effect="dark"
                          content="确定数据无误后，将无法修改和删除,确定后的数据销售才可见" placement="top"
              >
                <el-button v-permission="'confirm_account_received'" type="warning"
                           size="mini"
                           @click="confirmAccountReceived(scope.row.id)"
                >
                  确认
                </el-button>
              </el-tooltip>
              <el-button class="group_btn" v-if="!scope.row.confirm" v-permission="'remove_account_received'"
                         type="danger" size="mini"
                         @click="removeAccountReceived(scope.row.id)"
              >删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      :current-page.sync="searchForm.page"
      :page-sizes="[10, 20, 50, 100, 200, 400]"
      :page-size.sync="searchForm.page_size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 10px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog :title="edit?'修改到款':'新增到款'" :visible.sync="centerDialogVisible" width="600px" center @close="closeDialog">
      <el-form ref="cuForm" style="width: 80%;margin: 0 auto" :model="cuForm" status-icon :rules="rules"
               label-width="100px" size="mini"
      >
        <el-form-item label="收款时间" prop="account_received_time">
          <el-date-picker v-model="cuForm.account_received_time"
                          style="width: 300px"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择收款时间"
          />
        </el-form-item>
        <el-form-item label="客户" prop="customer_id">
          <el-select v-model="cuForm.customer_id" style="width: 300px" filterable clearable>
            <el-option v-for="item in customerArr" :key="item.id" :value="item.id" :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="金额" prop="account">
          <el-input v-model="cuForm.account" clearable style="width: 300px" type="number" step="0.01"
                    placeholder="请输入到款金额"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" size="mini" @click="submitForm">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import SearchFormBox from '@/components/SearchFormBox'
import { company_list_all } from '@/api/customer/customer'
import { confirmBatch, edit, list, remove, save } from '@/api/accountReceived'

export default {
  name: 'AccountReceived',
  components: { SearchFormBox },
  data() {
    var checkAccount = (rule, value, callback) => {
      if (value === '' || value === null) {
        callback(new Error('请输入金额'))
      } else {
        const reg = /(^[1-9]{1}[0-9]*$)|(^[0-9]*\.[0-9]{2}$)/
        if (reg.test(value)) {
          callback()
        } else {
          callback(new Error('请输入合法金额'))
        }
      }
    }
    return {
      searchForm: {
        page: 1,
        page_size: 10,
        customer_id: null,
        begin_time: null,
        end_time: null
      },
      listParams: {
        page: 1,
        page_size: 10,
        customer_id: null,
        begin_time: null,
        end_time: null
      },
      customerArr: [],
      tableLoading: false,
      total: 0,
      listData: [],
      cuForm: {
        id: null,
        account_received_time: null,
        account: null,
        customer_id: null,
        confirm: null,
        deleted: null
      },
      centerDialogVisible: false,
      edit: false,
      rules: {
        account_received_time: [
          { required: true, message: '请选择到款时间', trigger: 'change' }
        ],
        customer_id: [
          { required: true, message: '请选择客户', trigger: 'change' }
        ],
        account: [
          { validator: checkAccount, trigger: 'blur' }
        ]
      },
      selectArr: []
    }
  },
  created() {
    this.getCustomerList()
    this.getList()
  },
  methods: {
    handleSizeChange(val) {
      this.listParams.page_size = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listParams.page = val
      this.getList()
    },
    getList() {
      this.tableLoading = true
      list(this.listParams).then(res => {
        this.listData = res.data.records
        this.total = res.data.total
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    search() {
      this.listParams = Object.assign({}, this.searchForm)
      this.getList()
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.search()
    },
    getCustomerList() {
      // 获取项目列表
      company_list_all().then(res => {
        this.customerArr = res.data.map(item => {
          return {
            id: item.id,
            name: item.name
          }
        })
      })
    },
    removeAccountReceived(id) {
      this.$confirm('是否确定删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '操作中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        remove({ id }).then(res => {
          this.$message.success('操作成功')
          loading.close()
          this.getList()
        }).catch(() => {
          loading.close()
        })
      }).catch(() => {

      })
    },
    confirmAccountReceived(id) {
      this.confirmAccountReceivedArr([id])
    },
    confirmAccountReceivedArr(arr) {
      this.$confirm('确认后的付款将无法修改，是否确定？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '操作中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        confirmBatch(arr).then(res => {
          this.$message.success('操作成功')
          loading.close()
          this.getList()
        }).catch(() => {
          loading.close()
        })
      }).catch(() => {

      })
    },
    showEditDialog(row) {
      this.centerDialogVisible = true
      this.edit = true
      this.cuForm = Object.assign({}, row)
    },
    showAddDialog() {
      this.centerDialogVisible = true
    },
    closeDialog() {
      this.edit = false
      this.cuForm = {
        id: null,
        account_received_time: null,
        account: null,
        customer_id: null,
        confirm: null,
        deleted: null
      }
      this.$nextTick(() => {
        this.$refs.cuForm.clearValidate()
      })
    },
    submitForm() {
      this.$refs.cuForm.validate(flag => {
        if (flag) {
          const loading = this.$loading({
            lock: true,
            text: '提交中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          if (this.edit) {
            edit(this.cuForm).then(res => {
              this.$message.success('操作成功')
              this.centerDialogVisible = false
              this.getList()
              loading.close()
            }).catch(() => {
              loading.close()
            })
          } else {
            save(this.cuForm).then(res => {
              this.$message.success('操作成功')
              this.centerDialogVisible = false
              this.getList()
              loading.close()
            }).catch(() => {
              loading.close()
            })
          }
        }
      })
    },
    handleSelectionChange(val) {
      this.selectArr = val.map(item => {
        return item.id
      })
    },
    batchConfirm() {
      this.confirmAccountReceivedArr(this.selectArr)
    }
  }
}
</script>

<style scoped>
.page_main {
  padding: 20px;
}

.group_btn {
  float: left;
}
</style>
